module RenderTools

  def before_render_tools
    @page_tokens = Array.new
  end

  def after_render_tools
    clear_flash_messages
  end

  def self.included(base)
    base.send :helper_method, :page, :page_key
  end



  ##### MESSAGING #####
  def clear_flash_messages
    if @performed_render
      flash.delete(:error)
      flash.delete(:notice)
    end
  end
  ##### MESSAGING #####



  ##### PAGE KEY / PAGE TITLE #####
  def page_key
    "#{controller_name}_#{action_name}"
  end

  def page(item)
    string = Pages.instance.get(page_key,item) || ""
    replace_tokens(string)
  end

  def add_page_token(string)
    @page_tokens << string
  end
  ##### PAGE KEY / PAGE TITLE #####



  private

    def replace_tokens(string)
      unless string.blank?
        @page_tokens.size.times do |i|
          string = string.gsub("{#{i}}",@page_tokens[i]) || ''
        end
      end
      string
    end

end
